package getHardInfo

import (
	"bytes"
	"encoding/json"
	"io"
	"log"
	"net/http"
	rundebug "runtime/debug"
	"time"
)

func Posthttp(data map[string]interface{}, url string) {
	/*
		把map的json对象post到服务端api中
	*/
	// 创建要发送的 JSON 数据
	if data == nil {
		data = map[string]interface{}{
			"name":  "中文",
			"age":   30,
			"email": "alice@example.com",
		}
	}
	if url == "" {
		url = "https://getman.cn/echo"
	}
	// 将数据编码为 JSON
	jsonData, err := json.Marshal(data)
	if err != nil {
		log.Println("Error marshalling JSON:", err, rundebug.Stack())

	}

	// 创建 HTTP 请求

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		log.Println("Error creating request:", err, rundebug.Stack())

	}
	// 设置请求头
	req.Header.Set("Content-Type", "application/json")
	// 发送请求
	client := &http.Client{
		Timeout: 20 * time.Second,
	}
	resp, err := client.Do(req)
	if err != nil {
		log.Printf("发送请求出错 request:%v\n %s \n", err, rundebug.Stack())
		return
	}
	// for k, v := range resp.Header { // 打印头信息
	// 	log.Println(k, ":", v)
	// }
	body, err := io.ReadAll(resp.Body)
	//data, err := ioutil.ReadAll(file)
	defer resp.Body.Close()
	//log.Printf("返回状态码  =:%v", resp.StatusCode)
	//log.Printf("返回内容  Body  %T==: %s ", body, body)

	// 读取响应
	var response map[string]interface{}

	if err := json.Unmarshal(body, &response); err != nil {
		log.Printf("解析成json字典失败: %v\n %s \n", err, rundebug.Stack())
		log.Printf("Body  内容   %T==: %s ", body, body)
	} else {
		log.Printf("上报返回json数据 %T==: %v ", response, response)
		//暂时不错处理
	}

}
